﻿using System.Collections.Generic;
using System.Linq;

namespace ShopSpace.Core.Repositories.Impl
{
	internal class ProjectPersonRepository : RepositoryBase<ProjectPerson>, IProjectPersonRepository
	{
		public IList<ProjectPerson> ListByProject(Project project)
		{
			//DetachedCriteria criteria = DetachedCriteria.For<ProjectPerson>();
			//criteria.Add(Expression.Eq("Project.Id", project.Id));
			//criteria.CreateCriteria("Person")
			//    .AddOrder(Order.Asc("DisplayName"));
			//return this.GenericDAO.List<ProjectPerson>(criteria);
			var query = this.GenericDAO.AsQueryable<ProjectPerson>();
			query.Where(p => p.Project == project);
			query.OrderBy(p => p.Person.DisplayName);
			return query.ToList<ProjectPerson>();
		}

		public ProjectPerson GetByProjectAndPerson(Project project, Person person)
		{
			//DetachedCriteria criteria = DetachedCriteria.For<ProjectPerson>();
			//criteria.Add(Expression.Eq("Project.Id", project.Id));
			//criteria.Add(Expression.Eq("Person.Id", person.Id));
			//return this.GenericDAO.FindUnique<ProjectPerson>(criteria);
			return this.GenericDAO.FindFirst<ProjectPerson>(p => p.Person == person && p.Project == project);
		}

		public IList<ProjectPerson> ListAssignableToProject(Project project)
		{
			//IList<int> assignableRoles = new List<int>();
			//assignableRoles.Add(Convert.ToInt32(Role.Creator));
			//assignableRoles.Add(Convert.ToInt32(Role.Manager));
			//DetachedCriteria criteria = DetachedCriteria.For<ProjectPerson>();
			//criteria.Add(Expression.Eq("Project.Id", project.Id));
			//criteria.Add(Expression.InG<int>("Role", assignableRoles));
			//criteria.CreateCriteria("Person")
			//    .AddOrder(Order.Asc("DisplayName"));
			//return this.GenericDAO.List<ProjectPerson>(criteria);

			Role[] assignableRoles = { Role.Creator, Role.Manager };
			var query = from pp in this.GenericDAO.AsQueryable<ProjectPerson>()
						where pp.Project == project
						&& assignableRoles.Contains(pp.Role)
						orderby pp.Person.DisplayName
						select pp;
			return query.ToList<ProjectPerson>();

		}
	}
}